package com.zby.ss.core.factoryimpl;


import com.zby.ss.core.constants.FilterConstants;
import com.zby.ss.core.facotry.FileFactory;
import com.zby.ss.util.ArrayUtil;
import com.zby.ss.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created By zby on 11:18 2019/2/14
 */

public class FileFactoryImpl implements FileFactory {

    private static String reg = ".*\\.xml$";

    private static List<File> fileList = new ArrayList<>();

    private static Logger logger = LoggerFactory.getLogger(FileFactoryImpl.class);

    private static FileFactory fileFactory;

    /**
     * Created By zby on 14:15 2019/2/14
     * 返回老的的正则表达式
     *
     * @param regex 正则表达式
     */
    @Override
    public String modifyRegex(String regex) {
        String tmp = reg;
        if (StringHelper.isNotBlank(regex)) {
            reg = regex;
        }
        return tmp;
    }

    /**
     * Created By zby on 13:49 2019/2/14
     *
     * @param dir   文件目录
     * @param regex 正则表达式
     */
    @Override
    public File[] local(File dir, final String regex) {
        if (dir == null) {
            return null;
        }
        return dir.listFiles(new FilenameFilter() {
            private Pattern pattern = Pattern.compile(regex);

            @Override
            public boolean accept(File dir, String pathname) {
                return pattern.matcher(new File(pathname).getName()).matches();
            }
        });
    }

    /**
     * Created By zby on 14:02 2019/2/14
     *
     * @param path  文件路径
     * @param regex 正则表达式
     */
    @Override
    public File[] local(String path, final String regex) {
        return local(new File(path), regex);
    }

    /**
     * Created By zby on 14:42 2019/2/14
     * 获取文件夹的集合
     */
    @Override
    public List<File> listFile(File dir) {
        local(dir);
        return fileList;
    }

    /**
     * Created By zby on 14:04 2019/2/14
     * 获取文件的集合
     */
    private void local(File dir) {
        if (dir == null) {
            logger.error("文件夹为空dir=" + dir);
            throw new RuntimeException("文件夹为空dir=" + dir);
        }
        File[] fies = dir.listFiles();
        if (ArrayUtil.isNotEmpty(fies)) {
            for (File fy : fies) {
                if (fy.isDirectory()) {
                    local(fy);
                }
                String fileName = fy.getName();
                boolean isMatch = Pattern.compile(reg).matcher(fileName).matches();
                boolean isContains = ArrayUtil.containsAny(fileName, FilterConstants.FILE_NAMES);
                if (isMatch && !isContains) {
                    fileList.add(fy);
                }
            }
        }
    }
}
